#!/bin/bash
ver=''
var_num=$#
for var in $@
do
index=`echo $var| awk -F"=" '{print $1}'`;
var1=`echo $var| awk -F"=" '{print $2}'`;
[ $index == "-v" ]&&ver=$var1;
done
[ ! -f "./.env" ]&&touch ./.env
sed -i '/ver_tag/d' .env
echo ver_tag="$ver">>.env
now_ver="$(docker ps |  grep wecomscrm_dashboard |awk -F'[/"]' '{print $3}'  | awk -F':' '{print $2}')"                        #目前的版本tag
echo 当前版本为"$now_ver"
[ -e /tmp/"$now_ver"-easyink-sql ] &&  mv /tmp/"$now_ver"-easyink-sql /tmp/$(date +%Y-%m-%d-%H:%M)-easyink-sql-tmp
mv easyink-sql /tmp/"$now_ver"-easyink-sql
git clone https://gitee.com/lianluoyi/easyink-sql                                                                              #拉取最新sql
function version_gt() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"; }                                     #判断版本更新的函数
function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; }


echo $ver | grep -w 'V[1-9]\.[0-9]\+\.[0-9]\+' >/dev/null 2>&1                                                                 #进行目标版本核验
if [ $? == '0' ];then
  echo '版本一次核验成功'
else
  echo '版本核验失败'
  exit
fi

docker pull ccr.ccs.tencentyun.com/easyink/wecomscrm:$ver  >/dev/null 2>&1
if [ $? == '0' ];then
  echo '版本二次核验成功'
else
  echo '版本核验失败'
  exit
fi


mysql_tag=1
mysql_exist=`docker ps | grep wecommysql| awk -F" " '{print $3}'`                                                              #检查mysql是否为内置
if [ -n "$mysql_exist" ];then
  mysql_tag=1
  [ ! -d ./mysql/backup ]&&mkdir ./mysql/backup                                                                                #查看备份目录是否存在
  tar -czvf ./mysql/backup/$ver-mysql.tar.gz ./mysql/wecomdb                                                                   #备份数据库
  docker cp ./update-mysql.sh wecommysql:/update-mysql.sh                                                                      #拷贝升级脚本

  for sql in `ls ./easyink-sql`                                                                                                #循环比对版本大小
  do
    ver_sql=`echo "$sql" | awk -F ".sql" '{print $1}'|awk -F "-" '{print$2}'`
    if version_gt $ver_sql $now_ver;then
      echo "$ver_sql" "$now_ver"
      if  version_ge $ver $ver_sql;then                                                                                        #如果sql脚本版本比当前版本高，且不超过目标版本，就执行sql
      echo "$sql"
      docker cp ./easyink-sql/"$sql" wecommysql:/update.sql
      docker exec  wecommysql sh /update-mysql.sh >> /dev/null 2>&1
      fi
    fi
  done
else 
  mysql_tag=0
fi

redis_tag=1
redis_exist=`docker ps | grep wecomredis| awk -F" " '{print $3}'`
if version_gt 'V1.18.0' $now_ver && version_ge $ver 'V1.18.0';then
  if [ -z "$redis_exist" ];then
    redis_tag=0
  else
    echo "开始清理redis��数据: CurrentWeCorpAccount-new2:*"
    docker exec -it wecomredis /bin/bash -c "redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 keys "CurrentWeCorpAccount-new2:*" | xargs redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 del"
    echo "开始清理redis旧数据: getCorpRealTimeData-new2:*"
    docker exec -it wecomredis /bin/bash -c "redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 keys "getCorpRealTimeData-new2:*" | xargs redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 del"
    echo "开始清理redis旧数据: getCorpBasicData-new2:*"
    docker exec -it wecomredis /bin/bash -c "redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 keys "getCorpBasicData-new2:*" | xargs redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 del"
    echo "开始清理redis旧数据: CurrentWeCorpAccount-new2"
    docker exec -it wecomredis /bin/bash -c "redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 keys "CurrentWeCorpAccount-new2" | xargs redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 del"
    redis_tag=1
  fi
fi
if version_gt 'V1.29.2' $now_ver && version_ge $ver 'V1.29.2';then
  if [ -z "$redis_exist" ];then
    redis_tag=0
  else
    echo "开始清理redis旧数据: callbackEditCustomer:*"
    docker exec -it wecomredis /bin/bash -c "redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 keys "callbackEditCustomer:*" | xargs redis-cli -h 127.0.0.1 -p 6379 -a wecomscrm -n 10 del"
    redis_tag=1
  fi
fi



if version_gt 'V1.22.0' $now_ver && version_ge $ver 'V1.22.0';then
  cat ./env_file.env | grep LOGIN_RSA_PRIVATE_KEY
  if [ $? -ne 0 ];then
    echo "LOGIN_RSA_PUBLIC_KEY=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApjyS6WC57ViiJEd6WS9BrNgdAEtgONbEPPzdFMzlav5FKmefDBJXyPcdD2gdeN5CymWxcYd+suYu6f8D4xcvF9tmcAcI2ioUGCxcZLGQPtK4HoeAFEMLUaIlkl2Y2QvWwzXQ9QM8i20mC4X2O+Y8+oW8u1HmjyJpx074bL4+AFZbsQ+pRj+2uBbWg6o8DyP46DbQDIdtu08f/BHpbkGpP1TD86DMX2g59yJA+Gnje/An/qLuS/Ldekfel/tF4B6z+us8Z7fzBdODvkuaIYvR0LzRHOhDzbk43rGlciEG96PoSOQWo0N621jJive2MDKO/LdjjA+HquxlugRrfWE+wQIDAQAB">>env_file.env
    echo "LOGIN_RSA_PRIVATE_KEY=MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCmPJLpYLntWKIkR3pZL0Gs2B0AS2A41sQ8/N0UzOVq/kUqZ58MElfI9x0PaB143kLKZbFxh36y5i7p/wPjFy8X22ZwBwjaKhQYLFxksZA+0rgeh4AUQwtRoiWSXZjZC9bDNdD1AzyLbSYLhfY75jz6hby7UeaPImnHTvhsvj4AVluxD6lGP7a4FtaDqjwPI/joNtAMh227Tx/8EeluQak/VMPzoMxfaDn3IkD4aeN78Cf+ou5L8t16R96X+0XgHrP66zxnt/MF04O+S5ohi9HQvNEc6EPNuTjesaVyIQb3o+hI5BajQ3rbWMmK97YwMo78t2OMD4eq7GW6BGt9YT7BAgMBAAECggEAPrSg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NTcB2LrN9HWoDp/yyzJnTEOCJc7XxzpcfRZlzHicpgxL2QDHYlgdDPUxvShXZ2ogkCwTQkUo89LVr+LqlZ+l1NRfGXkFlpXx++zK7lifQVDjSxYL6oC0t00ny1/9upKIktc=">>env_file.env
    echo "add LOGIN_RSA_KEY complete!!"
  fi
fi
if version_gt 'V1.37.2.2' $now_ver && version_ge $ver 'V1.37.2.2';then
  cat ./env_file.env | grep SELF_BUILD_TOKEN
  if [ $? -ne 0 ];then
    echo "SELF_BUILD_TOKEN=3lTqc9EEO" >>env_file.env 
    echo "SELF_BUILD_ENCODING_AES_KEY=1K3K7DD74kbNNu58De5R7xoi2CyYxBdyxv8UHibVLoZ" >>env_file.env
    echo "add SELF_BUILD_TOKEN and SELF_BUILD_ENCODING_AES_KEY complete!!"
  fi
fi

docker ps -a | grep easywecom/elasticsearch&&sed -i s/easywecom/easyink/g ./docker-compose-es.yml&&docker-compose -f ./docker-compose-es.yml up -d
sed -i s/easywecom/easyink/g ./docker-compose-service.yml
docker-compose -f ./docker-compose-service.yml up -d
echo "版本升级结束，当前版本为$ver"
[ $mysql_tag -eq 0 ]&&echo "您使用的是外置MYSQL数据库，请先到'https://gitee.com/lianluoyi/easyink-sql'获取数据库更新文件并更新数据库，然后重启wescomscrm模块完成更新"
[ $redis_tag -eq 0 ]&&echo "您使用的是外置REDIS数据库，请先删除REDIS数据库中的CurrentWeCorpAccount-new2:*、getCorpRealTimeData-new2:*、getCorpBasicData-new2:*和CurrentWeCorpAccount-new2这四个KEY，然后重启wescomscrm模块完成更新"

